package com.lagou.kudu;

import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.Type;
import org.apache.kudu.client.CreateTableOptions;
import org.apache.kudu.client.KuduClient;
import org.apache.kudu.client.KuduException;

import java.util.LinkedList;

/**
 * @program: kuduHomework
 * @description:
 * @author: Mr.Wang
 * @create: 2021-03-05 11:25
 **/
public class CreateKuduTable {
	private static ColumnSchema newColumn(String name, Type type, Boolean isKey) {
		ColumnSchema.ColumnSchemaBuilder column =
				new ColumnSchema.ColumnSchemaBuilder(name, type);
		column.key(isKey);
		return column.build();
	}

	public static void main(String[] args) {
		String masterAddr = "node01";
		//创建kudu的数据库连接
		KuduClient client = new KuduClient.KuduClientBuilder(masterAddr)
				.defaultSocketReadTimeoutMs(6000).build();

		//设置表的schema
		LinkedList<ColumnSchema> columns = new LinkedList();

		columns.add(newColumn("id", Type.INT32, true));
		columns.add(newColumn("name", Type.STRING, false));
		Schema schema = new Schema(columns);

		//创建表时提供的所有选项
		CreateTableOptions options = new CreateTableOptions();
		//设置表的replica备份和分区规则
		LinkedList<String> parcols = new LinkedList();
		parcols.add("id");
		//设置表的备份数
		options.setNumReplicas(1);
		//设置hash分区和数量
		options.addHashPartitions(parcols, 3);
		try {
			//创建表
			client.createTable("student",schema,options);
		} catch (KuduException e) {
			e.printStackTrace();
		} finally {
			try {
				if(client != null){
					client.close();
				}
			} catch (KuduException e) {
				e.printStackTrace();
			}
		}
	}
}
